<template>
  <div :class="{ 'dark-theme': isDark }">
    <s-nav-bar v-show="shellShow" color="#666" bg="#fff">
      <div class="fc vh-c ac-nb-item">
        <van-icon name="wap-home-o" />
        <router-link to="/home">首页</router-link>
      </div>
    </s-nav-bar>
    <tab-bar v-show="shellShow" @near="toRecentPage" @theme="isDark = !isDark" @list="show = !(shellShow = show)"
      @config="fontSizeConfig">
    </tab-bar>
    <div id="content" class="content-wrap" :style="{ fontSize: fontSize + 'px' }">
      <div v-show="!contentShow" class="loading-outer">
        <van-loading type="spinner" size="24px" vertical>加载中...</van-loading>
      </div>
      <div v-show="contentShow">
        <!-- 下拉加载 -->
        <pull-load :pullfresh="downPullFresh" text="下拉阅读上一章"
          :freshText="datalist.prev ? datalist.prev.name : '已是第一章'"></pull-load>

        <!-- 文章正文 -->
        <content-wrap :title="datalist.title" :body="datalist.content"></content-wrap>

        <!-- 上拉加载 -->
        <pull-load :pullfresh="upPullFresh" text="上拉阅读下一章"
          :freshText="datalist.next ? datalist.next.name : '已是最后一章'"></pull-load>
      </div>
    </div>
    <van-popup v-model="show" position="left" :style="{ width: '75%', height: '100%' }" @open="shellShow = false"
      @close="shellShow = true">
      <span class="sec-label">共 {{ datalist.totalCount }} 章</span>
      <div class="pre-next">
        <span :class="{ 'not-pre-next': pageNo <= 0 }" @click="changeList('pre')">
          上{{ listMax }}章
        </span>
        <span :class="{ 'not-pre-next': pageNo >= totalPage }" @click="changeList('next')">
          下{{ listMax }}章
        </span>
      </div>
      <section-list @link="changeArticle" :data="curChapterList"></section-list>
      <div class="pre-next">
        <span :class="{ 'not-pre-next': pageNo <= 0 }" @click="changeList('pre')">
          上{{ listMax }}章
        </span>
        <span :class="{ 'not-pre-next': pageNo >= totalPage }" @click="changeList('next')">
          下{{ listMax }}章
        </span>
      </div>
    </van-popup>
  </div>
</template>

<script>
import sNavBar from '@/components/sNavBar.vue'
import TabBar from '@/components/TabBar.vue'
import SectionList from '@/components/SectionList.vue'
import PullLoad from '@/components/PullLoad.vue'
import ContentWrap from '@/components/ContentWrap.vue'
const dbltouch = function (times = 300) {
  let timer = null;
  let cnt = 0;
  return function (cb) {
    if (timer && cnt == 0) {
      cnt++;
      cb();
    }
    timer = setTimeout(() => {
      timer = null;
      cnt = 0;
    }, times)
  }
};
export default {
  components: {
    sNavBar,
    TabBar,
    PullLoad,
    ContentWrap,
    SectionList
  },
  data() {
    return {
      appDom: document.getElementById('app'),
      datalist: [],
      allChapterList: [], // 完整章节列表
      pageNo: 0, //当前页位置
      totalPage: 0, //总页数
      listMax: 100, //目录长度
      isDark: false, //是否夜间模式
      fontSize: 16, //字号
      show: false, //是否显示侧边栏
      contentShow: false,//是否显示正文
      shellShow: true, //是否显示顶部、底部导航条
      shellShowImportant: false, //是否显示顶部、底部导航条
      pathStr: this.$route.params.path, // 当前章节path
      rootPathStr: this.$route.params.rootPath, // 书籍信息path
      // $route.params.data 最近阅读的数据
      downPullFresh: false, //是否显示下拉刷新组件
      upPullFresh: false, //是否显示上拉刷新组件
    }
  },
  computed: {
    curChapterList() {
      let { pageNo, listMax, allChapterList } = this;
      return (allChapterList || []).slice(pageNo * listMax, (pageNo + 1) * listMax);
    },
  },
  created() {

    this.getContent()

  },
  mounted() {
    let { appDom } = this;
    appDom.addEventListener('scroll', this.scrollEvent)
    window.addEventListener('touchend', this.touchEnd)
    window.addEventListener('touchmove', this.touchmove)
  },
  destroyed() {
    let { appDom } = this;
    appDom.removeEventListener('scroll', this.scrollEvent)
    window.removeEventListener('touchend', this.touchEnd)
    window.removeEventListener('touchmove', this.touchmove)
  },
  methods: {
    // 一些事件处理
    scrollEvent() {
      let docEl = this.appDom;
      let scrollTop = docEl.scrollTop;
      if (scrollTop <= 0) {
        this.scrollType = 'top';
      } else if (scrollTop >= docEl.scrollHeight - docEl.clientHeight) {
        this.scrollType = 'bottom';
      } else {
        this.shellShow = this.shellShowImportant || false;
        this.shellShowImportant = false; // 重置，防止在设置字体的时候发生滚动导致控制组件隐藏
        this.scrollType = null;
        this.downPullFresh = false;
        this.upPullFresh = false;
      }
    },
    touchEnd() {
      //双击事件
      this.dbltouch(() => {
        if (!this.show) {
          this.shellShow = true
        }
      })
      const { prev, next } = this.datalist;
      if (this.scrollType == 'top') {
        // 加载前一章
        if (prev && this.downPullFresh) {
          this.getContent(prev.path)
          this.downPullFresh = false;
        }
      } else if (this.scrollType == 'bottom') {
        // 加载下一章
        if (next && this.upPullFresh) {
          this.getContent(next.path)
          this.upPullFresh = false;
        }
      }
    },
    touchmove() {
      if (this.scrollType == 'top') {
        // 加载前一章刷新组件显示
        this.downPullFresh = true;
      } else if (this.scrollType == 'bottom') {
        // 加载下一章刷新组件显示
        this.upPullFresh = true;
      }
    },
    dbltouch: dbltouch(),

    getContent(pathStr) {
      if (pathStr) {
        this.pathStr = pathStr;
      }
      this.appDom.scrollTo(0, 0);
      this.contentShow = false;
      this.$bqg.getContent(this.pathStr, this.rootPathStr, this.listMax).then(res => {
        const { pageNo, totalPage, list, ...rest } = res;
        this.datalist = rest;
        this.totalPage = totalPage;
        this.pageNo = pageNo;
        this.allChapterList = Object.freeze(list);
        this.contentShow = true;
        this.addRecentRead(); // 添加最近阅读
      })
    },
    changeArticle(path) {
      this.show = false; // 关闭侧边弹窗
      this.getContent(path); // 获取数据
    },
    toRecentPage() {
      this.$router.push('/recentread')
    },
    addRecentRead() {
      const recentRead = localStorage.getItem('xy_recentRead') || "[]";
      const jsonObj = JSON.parse(recentRead);
      const curbook = {
        data: this.$route.params.data,
        path: this.pathStr,
        rootPath: this.rootPathStr,
        title: this.datalist.title
      };

      let findItem = jsonObj.find((book) => {
        return book.rootPath == curbook.rootPath
      })
      if (findItem) {
        findItem.path = curbook.path;
        findItem.title = curbook.title;
      } else {
        jsonObj.unshift(curbook)
      }

      localStorage.setItem('xy_recentRead', JSON.stringify(jsonObj.slice(0, 10)))
    },
    // 修改章节目录，列表由computed生成
    changeList(type) {

      switch (type) {
        case 'pre':
          if (this.pageNo > 0) {
            this.pageNo--
          }
          break;
        case 'next':
          if (this.pageNo < this.totalPage) {
            this.pageNo++
          }
          break;
      }

    },
    // 修改字体
    fontSizeConfig(type) {
      this.shellShowImportant = true;
      switch (type) {
        case 'add':
          if (this.fontSize < 24) {
            this.fontSize += 2
          } else {
            this.$toast('已是最大字号')
          }
          break;
        case 'sub':
          if (this.fontSize > 12) {
            this.fontSize -= 2
          } else {
            this.$toast('已是最小字号')
          }
          break;
      }
    },
  },


}
</script>

<style>
.ac-nb-item>a {
  font-size: 12PX !important;
}

.ac-nb-item {
  margin-left: 25px;
}

/* 夜间模式 */
.dark-theme .van-nav-bar,
.dark-theme .tabbar,
.dark-theme .set-wrap {
  background: #343434 !important;

}

.dark-theme .van-popup,
.dark-theme .content-wrap {
  background: #2f2f2f !important;
  color: #787878 !important;
}

.dark-theme .van-loading,
.dark-theme .van-loading__text {
  color: #787878 !important;
}

.dark-theme .set-wrap>span {
  border-color: #5e5e5e;
}

.tabbar {
  background: #fff;
  color: #666;
}

/* 正文容器 */
.content-wrap {
  padding: 0 15PX;
  margin-top: -50PX;
  box-sizing: border-box;
  overflow: hidden;
  min-height: 100vh;
  background: #f7f5f2;
  position: relative;
}

.loading-outer {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
}

/* 侧边栏 */
.sec-label {
  font-size: 15px;
  margin-left: 15px;
  color: #ABA499;
}

.pre-next {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
}

.pre-next span {
  font-size: 14px;
  border: 1px solid #ff976a;
  color: #ff976a;
  border-radius: 5px;
  padding: 8px 35px;
}

.pre-next span.not-pre-next {
  border: 1px solid #ddd;
  color: #ddd;
}
</style>